<script setup lang="jsx">
  import {watch,inject,ref,reactive} from 'vue'
  import { Message } from '@arco-design/web-vue'
  import uploadConfig from '@/config/upload'
  import tool from '@/utils/tool'
  import commonApi from '@/api/common'
  import Attachment from '@/api/document/attachment'
  import {request} from "@/utils/request.js";
  const crudRef = ref()
  const record = inject('record')
  const fileData = inject('fileData')
  watch(record,(newVal,oldVal)=>{
    if(newVal.id != undefined){
      console.log('刷新附件列表--'+record.value.id)
      crudRef.value.requestData()
    }
  })
  let options = reactive({
      id: 'customer_fee',
      pk: 'id',
      pageSize:100,
      autoRequest: record.value?.id > 0,
      showTools:false,
      expandSearch:false,
      // 右键菜单配置
      contextMenu: {
        // 是否开启右键菜单
        enabled: false,
      },
      isDbClickEdit:false,
      operationColumn: true,
      operationColumnWidth: 120,
      tablePagination:{style:{display:"none"}},
      api: Attachment.getList,
      beforeRequest:(param)=>{
        param.about_id = record.value.id
        return param;
      },
      beforeAdd:(param)=>{
        param.about_id = record.value.id
        return param;
      },
      add: {
        show: false,
        api: Attachment.save,
        auth: ['document:attachment:save'],
      },
      // edit: {
      //   show: true,
      //   api: Attachment.update,
      //   auth: ['document:attachment:update']
      // },
      delete: {
        show: true,
        batch: false,
        api: Attachment.deletes,
        auth: ['document:attachment:delete']
      },
    })

  const download = async (record) => {
    let url = ''
    let storeMode = getStoreMode(record.storage)
    console.log(record)
    if (storeMode !== 'LOCAL') {
      Message.info('处理中...')
      const domain = uploadConfig.storage[storeMode]
      url = domain + record.filepath
    } else {
      //文件上传在本地则请求后端下载
      Message.info('请求服务器下载文件中...')
      url = 'system/downloadById?id=' + record.id+'&type=attachment'
    }

    const response = await commonApi.download(url, 'get')
    if (response) {
      tool.download(response, (storeMode !== 'LOCAL') ? record.filename : '')
      Message.success('请求成功，文件开始下载')  
    } else {
      Message.error('文件下载失败')  
    }
  }
  const getStoreMode = (mode) => {
    return uploadConfig.storageMode[mode.toString()]
  }
const columns = ref([
  {title: '单据类型',hide: true,
  disabled:true,
  dataIndex: "about_type",
  addDefaultValue: fileData.value.type,
    dict: {
      name: "tagType",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
      },
    formType: "select",
    commonRules: {
      required: true,
      message: "请选择单据类型"
    }
  },
  {title: '附件类型',
  // hide: true,
  dataIndex: "attachable_type",
    dict: {
      name: "AttachmentType",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
      },
    formType: "select",
    commonRules: {
      required: true,
      message: "请选择附件类型"
    },
    onControl: (val, maFormObject) => {
      return {
        file_cover_type: {display: val == 1,},
      }
    }
  },
  {
    title: '覆盖类型',
    hide: true,
    addDisplay:false,
    dataIndex: "file_cover_type",
    addDefaultValue: ['1','2','3','4'],
    dict: {
      name: "file_cover_type",
      props: {
        label: "title",
        value: "key"
      },
      translation: true
      },
    formType: "checkbox",
    commonRules: {
      required: true,
      message: "请选择附件类型"
    },
  },
  {title: '文件', 
    dataIndex: 'file',
    type: "file",
    editDisplay: false,
    formType: "upload",
    hide:true,
    commonRules: {
      required: true,
      message: "请上传文件"
    }
  },
  {title: '', dataIndex: 'about_id',
    addDefaultValue:record.value.id,addDisplay: false,editDisplay: false,
    hide:true,
  },
  {title: '文件名', dataIndex: 'filename',addDisplay: false,editDisplay: false,},
  {title: '客户可见', dataIndex: 'user_visible',formType: "select",
  dict: {
      data:[
        {
          label: '是',
          value: '1'
        },
        {
          label: '否',
          value: '0'
        },
      ],
      translation: true,
    },
    },
  {title: '上传人',formType: "select", dataIndex: 'created_by',addDisplay: false,editDisplay: false,
    dict: {
        url: 'system/user/list',
        props: {label: 'nickname', value: 'id'} ,
        params: {select: 'id,nickname'},
      translation: true,
    },
  },
  {title: '上传时间', dataIndex: 'created_at',addDisplay: false,editDisplay: false,},
]);

const downloadAll = () => {
  let data = {id:record.value.id}
      const download = (url) => request({url,data , method: 'post', timeout: 60 * 1000, responseType: 'blob'})
     download('document/attachment/downloadAll').then(res => {
        tool.download(res)
        Message.success('请求成功，文件开始下载')
      }).catch((res) => {
        res.text().then((text) => {
          Message.error(JSON.parse(text).message)
        })
      })
}
</script>

<template>
  <a-grid-item :span="fileData.span">
    <a-collapse :default-active-key="['1']" class="g-collapse-no-p">
      <a-collapse-item header="附件" key="1">
        <template #extra>
          <a-button-group>
            <a-button type="primary" size="mini" @click.stop="downloadAll()" ><icon-download />批量下载</a-button>
            <a-button type="primary" size="mini" @click.stop="crudRef.addAction()" v-auth="['document:attachment:save']"><icon-upload />上传</a-button>
          </a-button-group>
        </template>
          <ma-crud :options="options" :columns="columns" ref="crudRef" class="file-list">
            <template #operationBeforeExtend="{ record }">
              <a-link @click="download(record)"><icon-download /> 下载</a-link>
            </template>
          </ma-crud>
      </a-collapse-item>
    </a-collapse>
  </a-grid-item>
</template>
<style>
.file-list ._crud-header,.file-list .mb-2,.file-list .operation-tools,.file-list .mb-1{
  display:none;
}

</style>